package com.dmm.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.dmm.redis.service.redisService;
import com.dmm.user.entity.User;
import com.dmm.user.mapper.UserMapper;
import com.dmm.user.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.mail.*;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Random;

/**
 * <p>
 * 用户信息 服务实现类
 * </p>
 *
 * @author dmm
 * @since 2022-10-13
 */

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    UserMapper userMapper;

    @Resource
    redisService redisService;

    @Override
    @Cacheable(value = "redisCache", key = "'user_FindAll'+#id")
    public User FindAll(Integer id) {
        User user = userMapper.selectById(id);
        return user;
    }



    //登录
    @Override
    public User getemail(String email, String password) {

        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("email",email);
        User user = baseMapper.selectOne(queryWrapper);
        if(user!=null){
            if(user.getPassword().equals(password)){
                return user;
            }
        }
        return null;
    }


    //注册
    @Override
    public Boolean register(User user,String code) {

        String s = redisService.get(user.getEmail());

        if(s.equals(code)){
            int insert = baseMapper.insert(user);
            return (insert>0)?true:false;
        }

        return false;
    }


    //验证码的获取

    @Override
    public void getCode(String email) {
        String str= "";

        for(int i=0;i<6;i++){
            str=str+new Random().nextInt(10);
        }

        log.info(str);



        //将验证码存入redis
        redisService.set2(email,str,1);

        // 发送验证码到邮箱
        Email email1 = new SimpleEmail();


        try {
            email1.setHostName("smtp.qq.com");
            //端口号
            email1.setSmtpPort(465);

            email1.setCharset("utf-8");//设置发送的字符类型
            email1.addTo(email);//设置收件人
            email1.setFrom("1458119489@qq.com");//发送人的邮箱为自己的，用户名可以随便填
            //设置发送人到的邮箱和用户名和授权码(授权码是自己设置的)
            email1.setAuthenticator(new DefaultAuthenticator("1458119489@qq.com","jeudwbynfknlibee"));

            email1.setSSLOnConnect(true);

            email1.setSubject("注册验证码");//设置发送主题
            email1.setMsg("验证码有效时间1分zhong"+str);//设置发送内容
            email1.send();//进行发送

        } catch (EmailException e) {
            e.printStackTrace();
        }


    }
}
